package com.baidu.voice;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;

public class MainActivity extends Activity implements OnClickListener {
    
	private static final int LOAD_DIALOG = 1;
	
	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
	
	private static final String BASE_URL = "http://wap.baidu.com/s?word=";
	
	private WebView webView;
	
	private EditText keywords;
	
	private Button btnVoice;
	
	private Button btnSearch;	
	
	private Button exit;
	
	private FrameLayout adLayout;
    
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        
        adLayout = (FrameLayout)this.findViewById(R.id.ad_frame);
        
        btnVoice = (Button)this.findViewById(R.id.btn_voice);
        btnSearch = (Button)this.findViewById(R.id.btn_search);
        exit = (Button)this.findViewById(R.id.btn_close);
        keywords = (EditText)this.findViewById(R.id.keywords);
        
        //不让输入框一开始就获得焦点
        keywords.clearFocus();        
        btnSearch.setOnClickListener(this);
        exit.setOnClickListener(this);
        
        webView = (WebView)this.findViewById(R.id.wv1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDefaultFontSize(17);
        webView.setWebViewClient(new WebViewClient(){  
            public boolean shouldOverrideUrlLoading(WebView view, String url) {  
            	view.loadUrl(url);               
                return true;  
            }  
            
            @Override
			public void onPageFinished(WebView view, String url) {
            	Log.d("WebView","onPageFinished");
            	//dismissDialog(LOAD_DIALOG);	   
            	adLayout.setVisibility(View.GONE);
            	webView.requestFocus();
				super.onPageFinished(view, url);
			}
            
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				Log.d("WebView","onPageStarted,url="+url);
				//showDialog(LOAD_DIALOG);    
				adLayout.setVisibility(View.VISIBLE);
				super.onPageStarted(view, url, favicon);
			}
        });  
        
   
        
        //进入则直接加载语音窗口
        // Check to see if a recognition activity is present
        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() != 0) {
        	btnVoice.setOnClickListener(this);
        	startVoiceRecognitionActivity();
        } else {
        	btnVoice.setEnabled(false);
        }
        
        
    }
    
    public void onClick(View v) {
    	switch(v.getId())
    	{
    		case R.id.btn_voice:
    			startVoiceRecognitionActivity();
    			break;
    		case R.id.btn_search:
    			//隐藏掉键盘
    			InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);    
    			imm.hideSoftInputFromWindow(keywords.getWindowToken(), 0);    
    			//如果关键字不为空，则进行搜索
    			String key = keywords.getText().toString();
    			if(!"".equals(key)){
    				webView.loadUrl(BASE_URL+key);
    			}
    			break;    
    		case R.id.btn_close:
    			webView.clearCache(true);
    			this.finish();
    			super.onDestroy();
    			break;
    	}        
    }
    
    
    /**
     * Fire an intent to start the speech recognition activity.
     */
    private void startVoiceRecognitionActivity() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "语音输入...");
        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
    }

    /**
     * Handle the results from the recognition activity.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
            // Fill the list view with the strings the recognizer thought it could have heard
            ArrayList<String> matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
            if(matches!=null && !matches.isEmpty()){
            	keywords.setText(matches.get(0));
            	webView.loadUrl(BASE_URL + matches.get(0));
            }else{
            	webView.loadUrl(BASE_URL);
            }
        }else{
        	webView.loadUrl(BASE_URL);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {           
            case LOAD_DIALOG: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage("Loading...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
       }
       return null;
    }
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {  
        	if(webView.canGoBack()){
        		webView.goBack();          		
                return true; 
        	}
        }  
        return super.onKeyDown(keyCode, event);  
    }  
        
}